<template>
  <div class="app-container">
    <el-row class="pl-10" type="flex" justify="start" :gutter="20">
      <el-button type="success" @click="showDialog('新增')">新增部门</el-button>
    </el-row>
    <div class="mt-20">

      <el-tree v-if="reTree"
        :props="treeProps"
        :load="loadNode"
        lazy
        :expand-on-click-node="false"
        >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button v-if="node.level!=5"
              type="text"
              size="mini"
              @click="() => showChildDialog('添加子部门',data,node)">
              添加子部门
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => showDialog('编辑',node)">
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => showComfirm(node,data)">
              删除
            </el-button>
          </span>
        </span>
      </el-tree>

    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="dialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="form.departmentName"></el-input>
        </el-form-item>
        <el-form-item label="部门描述" prop="departmentDesc">
          <el-input type="textarea" :rows="2" v-model="form.departmentDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="childDialogTitle"
      :visible.sync="childDialogVisible"
      width="40%"
      :before-close="childDialogClose">
      <el-form ref="childForm" :model="childForm" :rules="childRules" label-width="100px">
        <el-form-item label="子部门名称" prop="departmentName">
          <el-input v-model="childForm.departmentName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="childDialogClose">取 消</el-button>
        <el-button type="primary" @click="addOrEditChild">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {findParentDeptList,findChildrenDeptList,findDeptDetail,addDept,updateDept,deleteDept} from '@/api/departPersonManage/departManagement'
import {departManagementTreeData} from '@/constants/mockDatas'
import {deleteConfirm} from '@/utils/deleteConfirm'
import {requireInput} from '@/utils/validateForm'

export default {
  data() {
    return {
      reTree: true,
      treeProps: {
        label: 'departmentName',
        children: 'zones',
        isLeaf: 'leaf'
      },
      treeData: [],
      dialogVisible: false,
      dialogTitle: '添加部门',
      childDialogVisible: false,
      childDialogTitle: '添加子部门',
      form: {
        departmentName: '',
        departmentDesc: '',
      },
      childForm: {
        departmentName: '',
        parentDepartment: '',
      },
      rules: {
        departmentName: requireInput('请输入部门名称'),
      },
      childRules: {
        departmentName: requireInput('请输入子部门名称'),
      },
      departmentId: 0,
      nodeData: {},
      node: null,
    }
  },
  created() {

  },
  methods: {
    async loadNode(node, resolve) {

      if (node.level === 0) {
        let {code,data,msg} = await findParentDeptList();
        if(code == '00000') {
          this.treeProps = {
            label: 'departmentName',
            children: 'zones',
            isLeaf: 'leaf'
          };
          return resolve(data);
        }

      }

      let {code,data,msg} = await findChildrenDeptList({
        departmentId: node.data.departmentId
      });
      resolve(data);

    },

    showDialog(type, node = false) {
      this.dialogTitle = type;
      if (node) {
        this.departmentId = node.data.departmentId;
        this.findDeptDetailAsync();
        // for(let i in node.data) {
        //   if(this.form.hasOwnProperty[i]) {
        //     this.form[i] = node.data[i]
        //   }

        // }
      }else {
        this.form = {
          departmentName: '',
          departmentDesc: '',
        },
        this.dialogVisible = true;
      }

    },

    showChildDialog(type,data, node) {
      this.childDialogTitle = type;
      this.nodeData = data;
      this.childForm.parentDepartment = data.departmentId
      if(type=='添加子部门') {
        this.childForm.departmentName = '';
      }else {

      }


      this.childDialogVisible = true;
    },

    addOrEdit() {
      this.$refs.form.validate(valid=>{
        if(valid) {
          if (this.dialogTitle == "新增") {
            this.addDeptAsync(this.form);
          } else {
            this.updateDeptAsync();
          }


        }
      })

    },

    dialogClose() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },

    childDialogClose() {
      this.$refs.childForm.resetFields();
      this.childDialogVisible = false;
    },

    addOrEditChild() {
      this.$refs.childForm.validate(valid=>{
        if(valid) {
          if (this.childDialogTitle == "添加子部门") {
            this.addDeptAsync(this.childForm);
          } else {
            this.updateDeptAsync();
          }


        }
      })

    },

    showComfirm(node,data) {
      this.node = node;
      this.nodeData = data;
      this.departmentId = data.departmentId;
      deleteConfirm(this, this.deleteDeptAsync);
    },


    async findDeptDetailAsync() {
      let {code,data,msg} = await findDeptDetail({
        departmentId: this.departmentId
      });
      if(code=='00000') {
        for(let i in data) {
          if(this.form.hasOwnProperty(i)) {
            this.form[i] = data[i]
          }
          if(this.childForm.hasOwnProperty(i)) {
            this.childForm[i] = data[i]
          }
        }
        console.log(this.form);
        this.dialogVisible = true;
      }
    },

    async addDeptAsync(formObj) {
      let {code,data,msg} = await addDept(formObj);
      if(code=='00000') {
        this.reTree = false;
        setTimeout(()=>{
          this.reTree = true;
          this.dialogVisible = false;
          this.childDialogVisible = false;
        },1)
      }
    },

    async updateDeptAsync() {
      let idObj = {departmentId:this.departmentId}
      let form = {...idObj,...this.form}
      let {code,data,msg} = await updateDept(form)
      if(code=='00000') {
        this.reTree = false;
        setTimeout(()=>{
          this.reTree = true;
          this.dialogVisible = false;
          this.childDialogVisible = false;
        },1)
      }
    },

    async deleteDeptAsync() {
      let {code,data,msg} = await deleteDept({
        departmentId: this.departmentId
      });
      if(code=='00000') {
        this.reTree = false;
        setTimeout(()=>{
          this.reTree = true;
        },1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });

        // const parent = this.node.parent;
        // console.dir(parent);
        // const zones = parent.data.zones || parent.data;
        // const index = zones.findIndex(d => d.departmentId === this.nodeData.departmentId);
        // zones.splice(index, 1);
      }
    }
  }
}
</script>
